<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>重置密码</span>
    </div>
    <!-- 表单 -->
    <el-form label-width="100px" :model="PwdForm" ref="PwdForm" :rules="rulesPwd">
      <el-form-item label="原密码" prop="old_pwd">
        <el-input v-model="PwdForm.old_pwd" type="password"></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="new_pwd">
        <el-input v-model="PwdForm.new_pwd"  type="password"></el-input>
      </el-form-item>
      <el-form-item label="确认新密码" prop="re_pwd">
        <el-input v-model="PwdForm.re_pwd" type="password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="updatePwd">修改密码</el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
export default {
  name: 'UserPwd',
  data () {
    const valinew = (rules, val, callback) => {
      if (val === this.PwdForm.old_pwd) {
        callback(new Error('新密码不能和旧密码一致'))
      } else {
        callback()
      }
    }
    const valire = (rules, val, callback) => {
      if (val !== this.PwdForm.new_pwd) {
        callback(new Error('两次密码输入不一致！'))
      } else {
        callback()
      }
    }
    return {
      PwdForm: {
        old_pwd: '',
        new_pwd: '',
        re_pwd: ''
      },
      rulesPwd: {
        old_pwd: [
          { required: true, message: '旧密码不能为空！' },
          { min: 6, max: 15, message: '密码长度6~15位之间！', trigger: 'blur' }
        ],
        new_pwd: [
          { required: true, message: '新密码不能为空！' },
          { min: 6, max: 15, message: '密码长度6~15位之间！', trigger: 'blur' },
          { validator: valinew, trigger: 'blur' }
        ],
        re_pwd: [
          { required: true, message: '确认密码不能为空！' },
          { validator: valire, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    updatePwd () {
      // 兜底校验
      this.$refs.PwdForm.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.patch('/my/updatepwd', this.PwdForm)
        if (res.code !== 0) return
        this.$refs.PwdForm.resetFields()
        //   更新vuex
        this.$store.dispatch('initUserInfo')
      })
    },
    reset () {
      this.$refs.PwdForm.resetFields()
    }
  }
}
</script>

<style lang="less" scoped>
.el-form {
  width: 500px;
}
</style>
